package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryTypeList() {
        //1.查询缓存
        String shopTypeJSON = stringRedisTemplate.opsForValue().get("cache:shop:type");
        //2.判断缓存是否存在
        if(StrUtil.isNotBlank(shopTypeJSON)){
            //存在，直接返回
            List<ShopType> list = JSONUtil.toList(shopTypeJSON, ShopType.class);
            return Result.ok(list);
        }
        //不存在，查询数据库
        List<ShopType> list = this.query().orderByAsc("sort").list();
        //判断是否存在于数据库
        if(list == null || list.isEmpty()){
            //不存在，返回错误信息
            return Result.fail("店铺类型不存在");
        }
        //存在，写入缓存
        stringRedisTemplate.opsForValue().set("cache:shop:type", JSONUtil.toJsonStr(list));

        return Result.ok(list);
    }
}
